#include "sshcreateguide.h"
#include "ui_sshcreateguide.h"

#include <QSqlRecord>
#include <QSqlError>

SshCreateGuide::SshCreateGuide(QWidget *parent)
    : QDialog(parent)
    , ui(new Ui::SshCreateGuide)
{
    ui->setupUi(this);
    this->setWindowFlag(Qt::Dialog);
    this->setWindowTitle("新建ssh连接");
    InitListView();
    ConnectAll();
}

SshCreateGuide::~SshCreateGuide()
{
    delete ui;
    mDataBase.close();
}

// private:

void SshCreateGuide::CreateNewSshConsole(const Ssh::SshLoginKeys& loginKeys)
{
    const auto sshConsole = new SshConsole(loginKeys, this);
    sshConsole->SetPrompt(QString::fromStdString(loginKeys.user + "@" + loginKeys.host + std::to_string(loginKeys.port) + " "), true);
    emit RequestCreateSshConsole(sshConsole);
    this->accept();
}

void SshCreateGuide::InitListView()
{
    mDataBase.setDatabaseName("loginKeys.db");

    // 打开db数据库
    if (!mDataBase.open()) {
        qCritical() << "Error: Unable to open database";
        return;
    }

    // 创建一个表，如果不存在
    if (!mQuery.exec("CREATE TABLE IF NOT EXISTS loginKeys (hst TEXT PRIMARY KEY, usr TEXT, prt INTEGER, pwd TEXT)")){
        qCritical() << "Error: Unable to create table";
        return;
    }

    // 插入数据
    if (!mQuery.exec("INSERT INTO loginKeys (hst, usr, prt, pwd) VALUES ('172.22.78.205', 'shz', 22, 'shz0905')")) {
        qDebug() << "22222222222";
    }

    // 创建tableModel
    mSqlTableModel = new QSqlTableModel(this, mDataBase);
    mSqlTableModel->setTable("loginKeys");
    mSqlTableModel->setEditStrategy(QSqlTableModel::OnRowChange);

    if (!mSqlTableModel->select()) {
        qCritical() << "Error: Unable to select table";
        return;
    }

    mSqlTableModel->setHeaderData(mSqlTableModel->fieldIndex("usr"), Qt::Horizontal, "用户");
    mSqlTableModel->setHeaderData(mSqlTableModel->fieldIndex("hst"), Qt::Horizontal, "主机");
    mSqlTableModel->setHeaderData(mSqlTableModel->fieldIndex("prt"), Qt::Horizontal, "端口");

    // 创建选择model
    mSelectionModel = new QItemSelectionModel(mSqlTableModel, this);
    // connect(mSelectionModel, &QItemSelectionModel::currentRowChanged, this, )

    // 更新listView
    ui->tableViewAllSsh->setModel(mSqlTableModel);
    ui->tableViewAllSsh->setSelectionModel(mSelectionModel);
    ui->tableViewAllSsh->setColumnHidden(mSqlTableModel->fieldIndex("pwd"), true);

    // 查询数据
    // mQuery.exec("SELECT * FROM loginKeys");
    // while (mQuery.next()) {
    //     QString hst = mQuery.value(0).toString();
    //     QString usr = mQuery.value(1).toString();
    //     int port = mQuery.value(2).toInt();
    //     QString password = mQuery.value(3).toString();
    //     qDebug() << "hst:" << hst << "usr:" << usr <<  "prt:" << port <<  "pwd:" << password;
    // }
}

void SshCreateGuide::ConnectAll()
{
    connect(ui->pushButtonConnect1, &QPushButton::clicked, this, [this] {
        this->CreateNewSshConsole(Ssh::SshLoginKeys{
            ui->lineEditUsr->text().toStdString(),
            ui->lineEditHst->text().toStdString(),
            ui->lineEditPrt->text().toInt(),
            ui->lineEditPwd->text().toStdString()
        });
    });

    connect(ui->pushButtonConnect2, &QPushButton::clicked, this, [this] {
        const auto row = mSelectionModel->currentIndex().row();
        const auto rec = mSqlTableModel->record(row);
        this->CreateNewSshConsole(Ssh::SshLoginKeys{
            rec.value("usr").toString().toStdString(),
            rec.value("hst").toString().toStdString(),
            rec.value("prt").toString().toInt(),
            rec.value("pwd").toString().toStdString(),
        });
    });

    connect(ui->pushButtonRemove, &QPushButton::clicked, this, [this] {
        const auto row = mSelectionModel->currentIndex().row();
        mSqlTableModel->removeRow(row);
        // 提交更改到数据库
        if (!mSqlTableModel->submitAll()) {
            qCritical() << "Failed to submit changes:" << mSqlTableModel->lastError();
        }
        // 刷新tableView
        mSqlTableModel->select();
        ui->tableViewAllSsh->reset();
    });

    connect(ui->pushButtonSave, &QPushButton::clicked, this, [this] {
        QSqlRecord rec = mSqlTableModel->record();
        rec.setValue(mSqlTableModel->fieldIndex("usr"), ui->lineEditUsr->text());
        rec.setValue(mSqlTableModel->fieldIndex("hst"), ui->lineEditHst->text());
        rec.setValue(mSqlTableModel->fieldIndex("prt"), ui->lineEditPrt->text().toUInt());
        rec.setValue(mSqlTableModel->fieldIndex("pwd"), ui->lineEditPwd->text());
        mSqlTableModel->insertRecord(0, rec);
        // mSelectionModel->clearSelection();
        // mSelectionModel->setCurrentIndex(index, QItemSelectionModel::Select);
    });
}
